


Na = Grids.Nx ;
ag = exp( linspace( - 10 * ParamsC.stdaCondx , ...
                    10 * ParamsC.stdaCondx  , ...
                    Na )' ) ;
da = [ ag(2:end) - ag(1:(end-1)) ; ag(end) - ag(end-1) ] ;                
                
RelPop = lognpdf( ag , - ParamsC.stdaCondx^2 / 2 , ParamsC.stdaCondx ) .* da ;

% check that mean is 1
sum( ag .* RelPop )

% define population distribution of workers
PopDistrib = popC * RelPop' ;
PopDistrib = PopDistrib / sum( PopDistrib(:) ) ;
sum( PopDistrib(:) )

% also for gamma = 3
PopDistribA = popA * RelPop' ;
PopDistribA = PopDistribA / sum( PopDistribA(:) ) ;
sum( PopDistribA(:) )

% rhs
popCa = popC * ag' ;
wCa   = whC * ones(size(ag))' ;

% standardize rhs
lpopCa = log(popCa) ;
lwCa   = log(wCa) ;

lpopCa = lpopCa / sqrt( Variance( lpopCa(:) , PopDistrib(:)  ) ) ;
lwCa   = lwCa   / sqrt( Variance( lwCa(:)   , PopDistrib(:)  ) ) ;

% lhs
sCa   = 100 * sC   * ones(size(ag))' ;
fCa   = 100 * fC   * ones(size(ag))' ;
uCa   = 100 * uC   * ones(size(ag))' ;
uCca  = uCa ./ ( 100 - uCa ) ;

uAa   = 100 * uA   * ones(size(ag))' ;


% means of lhs
mean_sCa  = sum( sCa(:)  .* PopDistrib(:) ) ;
mean_fCa  = sum( fCa(:)  .* PopDistrib(:) ) ;
mean_uCa  = sum( uCa(:)  .* PopDistrib(:) ) ;
mean_uCca = sum( uCca(:) .* PopDistrib(:) ) ;

% lhs relative to mean
uCaMean = uCca(:) / mean_uCca ;
sCaMean = sCa(:)  / mean_sCa ;
fCaMean = fCa(:)  / mean_fCa ;

% population weights
wt = popCa .* RelPop' ;

% prepare output for stata, with same names as data

Unorm         = uCca(:) / mean_uCca ; 
EUnorm        = sCa(:)  / mean_sCa  ;
UEnorm        = fCa(:)  / mean_fCa  ;

CitylWN       = lwCa(:)       ;
lCityPopN     = lpopCa(:)     ;
weights       = PopDistrib(:) ;

lUmUBase      = log( uCa(:) ./ ( 100 - uCa(:) ) ) ;
lThetaBase    = log( Theta( vC , zetaC ) ) * ag' ; lThetaBase = lThetaBase(:) ;

lUmUGamma3    = log( uAa(:) ./ ( 100 - uAa(:) ) ) ;
lThetaGamma3  = log( Theta( vA , zetaA ) ) * ag' ; lThetaGamma3 = lThetaGamma3(:) ;
weightsGamma3 = PopDistribA(:) ;

if options.SaveResults
    csvwrite_with_headers(...
            '/Users/adrien/Dropbox/JMP/7_statarev/source/correlationsVac.csv',...
            [Unorm,EUnorm,UEnorm,CitylWN,lCityPopN,weights,lUmUBase,lThetaBase,lUmUGamma3,lThetaGamma3,weightsGamma3],...
            {'Unorm','EUnorm','UEnorm','CitylWN','lCityPopN','weights','lUmUBase','lThetaBase','lUmUGamma3','lThetaGamma3','weightsGamma3'}) ;
end




